/**
 * MessageService.java Create on 2012-4-23     
*      
* Copyright (c) 2012-4-23 by yiming     
*      
* @author <a href="alenzhangym@hotmail.com">Yiming</a>     
* @version 1.0 
 */
package com.yimi.service;

import android.app.Service;
import android.util.Log;

import com.yimi.common.Message;

import java.util.Vector;

/**
 * TODO 功能描述    
 *      消息服务
 *  
 * @author Yiming
 * @version 1.0 
 */
public abstract class MessageService  extends Service{
    private String TAG = "MessageService";
	private Vector<Message> messages = new Vector<Message>();
	public abstract void sendNotify(Message message);
	protected StringBuffer lock = new StringBuffer("c");
	protected ReadThread readThread;
	public void onCreate(){
	    readThread = new ReadThread();
	    readThread.start();
	}
	public class ReadThread extends Thread {
		private boolean close;

		public ReadThread() {
			close = false;
		}

		public void run() {
			while (!close) {
				synchronized (lock) {
					if (close) {
						return;
					}
					if (messages.size() > 0) {
						Message message = messages.elementAt(0);
						Log.e(TAG, "message is "+message.toString());
						sendNotify(message);
						messages.remove(0);
					}
					try {
						lock.wait(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}

		/**
		 * 
		 */
		public void close() {
			close = true;
			synchronized (lock) {
				messages.removeAllElements();
				lock.notify();
			}
		}
	}
	
	public void addMessage(Message message) {
		if (message == null) {
			Log.i("SERVER ", "please don't add null message");
			return;
		}
		synchronized (lock) {
			this.messages.add(message);
			lock.notify();
		}
	}
	 public void onDestroy(){
	     readThread.close();
	     super.onDestroy();
	 }
}
